package com.kucun.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kucun.bean.Billdetail;
import com.kucun.bean.Page;
import com.kucun.bean.Users;
import com.kucun.service.Billdetailservice;
import com.kucun.util.ExportExcelUtil;
import com.kucun.util.GsonUtils;
import com.times.util.DateUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@Controller
@RequestMapping("/billdetail")
public class BilldetailController {
	private static final Logger logger = Logger.getLogger(BilldetailController.class.getName());
	@Autowired
	private Billdetailservice billdetailservice;
	
	/**
	 * 
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/getallbilldetail.html")
	public String getAllUser(int rows,int page,String cs,String filed,HttpServletRequest request,HttpServletResponse response) throws IOException{
		Page page1=new Page();
		page1.setI(rows*(page-1));
		page1.setRows(rows);
		page1.setObj(cs);
		if("".equals(filed)||filed==null){
			 
        }else{
        	filed = URLDecoder.decode(filed, "utf-8");
        } 
		page1.setFiled(filed);
		Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map  
		List<Billdetail> list = billdetailservice.findAll(page1);	
		jsonMap.put("total",billdetailservice.getCount(cs,filed).getTotal());//total键 存放总记录数，必须的  
        jsonMap.put("rows",list);//rows键 存放每页记录 list  
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);//格式化result   一定要是JSONObject  
        PrintWriter pw = response.getWriter();
        Object jsonFromBean=GsonUtils.ConvertJsonDateToDate(jsonObject,"yyyy-MM-dd HH:mm:ss");
        pw.write(jsonFromBean.toString());
		return null;
	}
	
	@RequestMapping("/querybilldetail.html")
	public String querybilldetail(Billdetail billdetail,int rows,int page,HttpServletRequest request,HttpServletResponse response) throws IOException{
		Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map  
		List<Billdetail> list = billdetailservice.query(billdetail,rows*(page-1),rows);	
		jsonMap.put("total",billdetailservice.queryCount(billdetail).getTotal());//total键 存放总记录数，必须的  
        jsonMap.put("rows",list);//rows键 存放每页记录 list  
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);//格式化result   一定要是JSONObject  
        PrintWriter pw = response.getWriter();
        pw.write(jsonObject.toString());
		return null;
	}

	/**
	 * @param user
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/updateuser.html")
	public void updateUser(Billdetail billdetail,HttpServletRequest request,HttpServletResponse response) throws IOException{
	    PrintWriter out = response.getWriter();
	    if (billdetail.getId()!=null) {
	    	if(billdetailservice.update(billdetail)){
	  			out.write("ok");
	  		}else{
	  			out.write("error");
	  		}
		}else{
			if(billdetailservice.save(billdetail)){
	  			out.write("ok");
	  		}else{
	  			out.write("error");
	  		}
		}
	  
	}
	

	/**
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/getUser.html")
	public String getUser(int id,HttpServletRequest request){
		
		request.setAttribute("user", billdetailservice.findById(id));
		return "/editUser";
	}
	/**
	 * @param id
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delet.html")
	public void delUser(String id,HttpServletRequest request,HttpServletResponse response){
		String result = "{\"result\":\"error\"}";
		String string=id;
		if(billdetailservice.delete(string)){
			result = "{\"result\":\"success\"}";
		}
		response.setContentType("application/json");
		try {
			PrintWriter out = response.getWriter();
			out.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	@RequestMapping("/savebilldate.html")
    @ResponseBody   // spring 异常统一处理方式
	public void Savebilldate(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Object result = 0;
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String tag=request.getParameter("tag");
		response.setContentType("application/json");
	    if("0".equals(tag)){ //新增保存
	    	result = billdetailservice.Savebilldate(request);
	    }else{  //编辑或者查看
	    	result = billdetailservice.updatebilldate(request);
	    }	
		if(result != null){
			jsonMap.put("success", true);
			jsonMap.put("status", result);
			JSONObject jsonObject = JSONObject.fromObject(jsonMap);
	        response.getWriter().write(jsonObject.toString());
	    }
		//spring 异常统一处理方式
		//throw new com.times.exception.BusinessException(Message.UPDATE_COLLECTION_OR_PAYMENT_DATE,"出库单！");

	}

	@RequestMapping("/querybilldatebyparentid.html")
	public void querybilldatebyParentid(HttpServletRequest request,HttpServletResponse response) throws IOException{       
		Billdetail map =new Billdetail();
		String billtype="";
		if(!"".equals(request.getParameter("billtype"))){
			 billtype = URLDecoder.decode(request.getParameter("billtype"), "utf-8");
		}
		String  parentid=request.getParameter("parentid");
		map.setParentid(Integer.valueOf(parentid));
		map.setBilltype(billtype);
		Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map 
		List<Billdetail> billlist=billdetailservice.querybilldatebyParentid(map); 
		jsonMap.put("total",billlist.size());//total键 存放总记录数，必须的  
        jsonMap.put("rows",billlist);//rows键 存放每页记录 list  
        PrintWriter pw = response.getWriter();
		//date类型的转化方式
	   // Object jsonFromBean=GsonUtils.ConvertJsonDateToDate(jsonMap,"yyyy-MM-dd HH:mm:ss");
	    Object jsonFromBean=GsonUtils.ConvertJsonDateToDate(jsonMap,"yyyy-MM-dd HH:mm:ss");
	    pw.write(jsonFromBean.toString()); 
	}
	@RequestMapping("/delbilldate.html")  //明细数据需要从数据库中 删除
	public void delBilldateById(String id,HttpServletRequest request,HttpServletResponse response) throws Exception{
		String result = "err";
		String row=request.getParameter("rows");
		if(!"".equals(row)){
			row=URLDecoder.decode(row, "UTF-8");
		}
		Users user=(Users)request.getSession().getAttribute("user");
		if(billdetailservice.deleteByPrimaryKey(Integer.valueOf(id))>0){
			logger.fatal(user.getUsername()+"于["+DateUtils.getStringDate()+"]删除了数据【"+row+"】");
			result = "ok";
		}
		try {
			PrintWriter out = response.getWriter();
			out.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	@RequestMapping("/upatebilldatebyids.html")  //明细数据需要从数据库中 删除
	public void upatebilldatebyids(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String result = "err";
		String row=request.getParameter("rows");
		if(!"".equals(row)){
			row=URLDecoder.decode(row, "UTF-8");
		}
		Users user=(Users)request.getSession().getAttribute("user");
		String ids=request.getParameter("ids");
		/***********删除明细数据，但是不实际删除*******后面需求要求直接数据库中删除*****/
		Object s=billdetailservice.updatebilldateToDel(ids);
		if((Boolean) s){
			result="ok";
			logger.fatal(user.getUsername()+"于["+DateUtils.getStringDate()+"]删除数据成功！数据【"+row+"】");
		}
			PrintWriter out = response.getWriter();
			out.write(result);	
	}
	
	@RequestMapping("/upatebilldatesubmitbyids.html")  //出库单提交数据
	public void upatebilldateToSubmitbyids(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String result = "err";
		String row=request.getParameter("rows");
		String billtype=request.getParameter("billtype");
		if(!"".equals(billtype)){
			billtype=URLDecoder.decode(billtype, "UTF-8");
		}
		if(!"".equals(row)){
			row=URLDecoder.decode(row, "UTF-8");
		}
		Users user=(Users)request.getSession().getAttribute("user");
		String ids=request.getParameter("ids");
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if("出库单".equals(billtype)){
			/**********验证当前选中数据中的数据是否满足库存限制****如果有数据超出库存值不允许提交返回超出物品数据作为提示**********/
			List<Billdetail> list=billdetailservice.VerifyInventory(ids);
	        if(list.size()>0){
	            jsonMap.put("rows",list);  
	            jsonMap.put("tag","err");
	        }else{
	        	/***********提交出库单数据************/
	    		boolean s=billdetailservice.updatebilldateToSubmit(ids,user);
	    		if(s){
	    		  	jsonMap.put("tag","ok");
	                jsonMap.put("rows","");//rows键 存放每页记录 list  
	    			logger.fatal(user.getUsername()+"于["+DateUtils.getStringDate()+"]提交数据成功！数据【"+row+"】");
	    		}else{
	    		  	jsonMap.put("tag","err");
	                jsonMap.put("rows","");//rows键 存放每页记录 list 
	    		}
	        }
		}else{  //入库单
			boolean s=billdetailservice.updatebilldateToSubmitOfInCome(ids,user);
    		if(s){
    		  	jsonMap.put("tag","ok");
                jsonMap.put("rows","");//rows键 存放每页记录 list  
    			logger.fatal(user.getUsername()+"于["+DateUtils.getStringDate()+"]提交数据成功！数据【"+row+"】");
    		}else{
    		  	jsonMap.put("tag","err");
                jsonMap.put("rows","");//rows键 存放每页记录 list 
    		}
		}
		
		
        Object jsonFromBean=GsonUtils.ConvertJsonDateToDate(jsonMap,"yyyy-MM-dd HH:mm:ss");
			PrintWriter out = response.getWriter();
			out.write(jsonFromBean.toString());	
	}
	
	
	/**
	 * 允许出库的物品
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/getgoodsexistout.html")
	public String GetGoodsExistOut(int rows,int page,HttpServletRequest request,HttpServletResponse response) throws IOException{
		   String q=request.getParameter("q");
	        String field=request.getParameter("field");
	        
	        String searchertext=request.getParameter("searchertext");
	        if(q!=null){ 
				field="specifications";
			}
	        if("".equals(searchertext)||searchertext==null){
	        	searchertext=q;
	        }else{
	        	searchertext = URLDecoder.decode(searchertext, "utf-8");
	        } 
		String clientid=request.getParameter("clientid");
       // System.out.println("clientid======"+clientid);
		Page page1=new Page();
		page1.setI(rows*(page-1));
		page1.setRows(rows);
		page1.setObj(clientid);
		page1.setFiled(field);
		page1.setSearchertext(searchertext);
		Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map  
		List<Billdetail> list = billdetailservice.GetGoodsExistOut(page1);	
		jsonMap.put("total",billdetailservice.GetGoodsExistOutCount(page1).getTotal());//total键 存放总记录数，必须的  
        jsonMap.put("rows",list);//rows键 存放每页记录 list  
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);//格式化result   一定要是JSONObject  
        PrintWriter pw = response.getWriter();
        pw.write(jsonObject.toString());
		return null;
	}
	
	/**
	 * 导出数据到excl中
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/getexporttoexcl.html")
	public void  GetExportToExcl(HttpServletRequest request,HttpServletResponse response) throws IOException{
		  String ids=request.getParameter("ids");
          String billtype=request.getParameter("billtype");
          Users user=(Users)request.getSession().getAttribute("user");
          if("".equals(billtype)||billtype==null){

          }else{
        	  billtype = URLDecoder.decode(billtype, "utf-8");
          } 
	        List<Billdetail> lists=null;
	        lists=billdetailservice.QueryBillDateByParentIDS(ids);
	        logger.info(user.getUsername() +" date:"+DateUtils.getStringDateShort()+"导出【"+billtype+"】"+JSONArray.fromObject(lists).toString());
		    String excelHeader="";   
		    if("入库单".equals(billtype)){
		    	 excelHeader="客户姓名#clientname,物品名称#goodname,规格型号#specifications,库存编号#beiyon,物品数量#goodnumber,物品单位#unit,SN#snno," +
		 		    	//	"仓库名称#repartoyname,货架#repartoyrack,货架位置#repartoyaddress,快递单号#couriernumber,物品去向#goodsgoout,单据类型#states" ;
		 		    	"仓库名称#repartoyname,货架#repartoyrack,货架位置#repartoyaddress,位置编号#positionnumber,备注#remark" ;
		 		    		//+",完成时间#createdate";     
		    }else{
		    	 excelHeader="客户姓名#clientname,物品名称#goodname,规格型号#specifications,库存编号#beiyon,物品数量#goodnumber,物品单位#unit,SN#snno," +
		 		    	//	"仓库名称#repartoyname,货架#repartoyrack,货架位置#repartoyaddress,快递单号#couriernumber,物品去向#goodsgoout,单据类型#states" ;
		 		    	"仓库名称#repartoyname,货架#repartoyrack,货架位置#repartoyaddress,位置编号#positionnumber,物品去向#goodsgoout" ;
		 		    		//+",完成时间#createdate";     
		    }
		    String totle="goodnumber";
		    String titleHander="操作人#leadingperson,操作时间#leadingtime";
		    try {
				ExportExcelUtil.exportOtherStyle(request,response, billtype, excelHeader, lists, null,titleHander);
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
	
}
